package com.fushi.demo.util;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

/**
 * Servlet Filter implementation class MyCoreFilter
 */
//@WebFilter(dispatcherTypes = {
//				DispatcherType.REQUEST, 
//				DispatcherType.FORWARD, 
//				DispatcherType.INCLUDE, 
//				DispatcherType.ERROR
//		}
//					, urlPatterns = { "/*" })
@Component
public class MyCoreFilter implements Filter {

    /**
     * Default constructor. 
     */
    public MyCoreFilter() {
        // TODO Auto-generated constructor stub
    	System.out.println("跨域访问过滤器启动");
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		HttpServletResponse res=(HttpServletResponse) response;
		HttpServletRequest req=(HttpServletRequest) request;
//		*代表任意的前端，哪怕和后端不同源的前端都可以访问后端资源
//		res.setHeader("Access-Control-Allow-Origin","http://localhost:8080");
		res.setHeader("Access-Control-Allow-Origin",req.getHeader("Origin"));
		res.setHeader("Access-Control-Allow-Headers",req.getHeader("Access-Control-Request-Headers"));
		res.setHeader("Access-Control-Allow-Credentials","true");
		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
